<template>
  <div class="app-container">
    <div class="page_header">{{ID?'编辑':'添加'}}服务人员</div>
    <el-col :span="16">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="12">
            <el-form-item label="登录名" prop="userName">
              <el-input :disabled="!!ID" v-model="formData.userName" placeholder="请输入单行文本登录名" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input :disabled="!!ID" v-model="formData.nickName" placeholder="请输入姓名" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <template v-if="!ID">
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="formData.password" placeholder="请输入密码" clearable show-password :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="确认密码" prop="checkPass">
                <el-input v-model="formData.checkPass" placeholder="请输入确认密码" clearable show-password :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="cardId">
              <el-input v-model="formData.cardId" placeholder="请输入身份证号" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phonenumber">
              <el-input v-model="formData.phonenumber" placeholder="请输入联系方式" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <treeselect style="width:300px;" @select="treeselectChange" v-model="formData.deptId" :options="deptOptions" filterable :show-count="true" placeholder="请选择部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="postIds">
              <el-select v-model="formData.postIds" multiple clearable placeholder="请选择职务" :style="{width: '100%'}">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分权配重" prop="servicePersonaProportion">
              <el-input-number v-model="formData.servicePersonaProportion" placeholder="分权配重" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="startData">
              <el-date-picker
                v-model="formData.startData"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择入职时间"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex" size="medium">
                <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="formData.school" placeholder="请输入毕业院校" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否禁用" prop="status">
              <el-radio-group v-model="formData.status" size="medium">
                <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技能" prop="servicePersonaFun">
              <el-checkbox-group v-model="formData.servicePersonaFun" size="medium">
                <el-checkbox v-for="(item, index) in servicePersonaFunOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居住地址" prop="addressArr">
              <CityPicker ref="cityPicker" size="small" clearable placeholder="请选择" v-model="formData.addressArr" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="addressDetail">
              <el-input v-model="formData.addressDetail" placeholder="请输入详细地址" :maxlength="100" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="合同人员" prop="personalType">
              <el-radio-group  v-model="formData.personalType" size="medium">
                <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.personalType=='0'" :span="12">
            <el-form-item label="开户行" prop="accountAddress">
              <el-input v-model="formData.accountAddress" placeholder="请输入开户行" :maxlength="100" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col  v-if="formData.personalType=='0'" :span="12">
            <el-form-item label="银行卡号" prop="accountNumber">
              <el-input v-model="formData.accountNumber" placeholder="请输入银行卡号" :maxlength="20" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col  v-if="formData.personalType=='0'" :span="12">
            <el-form-item label="开户姓名" prop="accountName">
              <el-input v-model="formData.accountName" placeholder="请输入开户姓名" :maxlength="100" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col  v-if="formData.personalType=='0'" :span="12">
            <el-form-item label="预留手机号" prop="accountPhone">
              <el-input v-model="formData.accountPhone" placeholder="请输入预留手机号" :maxlength="11" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- TODO: 限定地址 -->
            <el-form-item label="服务地址" prop="servicePersonalAreas">
              <div style="display:flex;align-items:flex-start;">
                <el-button style="height:32px;margin-top: 2px;" size="small" type="primary" icon="el-icon-plus" @click="handleAreaDataAdd">增加</el-button>
                <div style="margin-left:10px;">
                  <div v-for="(perCity,index) of formData.servicePersonalAreas" :key="index">
                    <CityPicker  size="small" clearable placeholder="请选择" v-model="formData.servicePersonalAreas[index]" />
                    <el-button
                      v-show="formData.servicePersonalAreas.length !== 1"
                      style="margin-left: 10px;"
                      size="small"
                      type="danger"
                      icon="el-icon-minus"
                      circle
                      @click="handleAreaDataMinus(index)"
                    ></el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large">
              <el-button type="primary" :disabled="pending" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-col>
  </div>
</template>

<script>
import CityPicker from '@/components/cityPicker'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getUser } from '@/api/system/user'
import { createCURD } from '@/api/sys'
const fetchApi = createCURD('personal')
export default {
  name: 'Personaledit',
  components: {
    CityPicker,
    Treeselect
  },
  data() {
    return {
      formData: {
        userName: undefined,
        nickName: undefined,
        password: undefined,
        checkPass: undefined,
        cardId: undefined,
        phonenumber: undefined,
        deptId: undefined,
        postIds: undefined,
        servicePersonaProportion: undefined,
        startData: null,
        sex: 0,
        school: undefined,
        status: 0,
        personalType:0,
        accountAddress:'',
        accountNumber:'',
        accountName:'',
        accountPhone:'',
        servicePersonaFun: [],
        addressArr: [],
        addressDetail: undefined,
        //
        servicePersonalAreas: [[]]
      },
      rules: {
        userName: [
          {
            required: true,
            message: '请输入登录名',
            trigger: 'blur'
          }
        ],accountPhone:[{
          required: true,
          message: '请输入开户预留手机号',
          trigger: 'blur'
        }],accountName:[{
          required: true,
          message: '请输入开户姓名',
          trigger: 'blur'
        }],accountNumber:[{
          required: true,
          message: '请输入银行卡号',
          trigger: 'blur'
        }],
        accountAddress:[{
          required: true,
          message: '请输入开户行',
          trigger: 'blur'
        }],personalType:[
          {
            required: true,
            message: '请选项是否合同人员',
            trigger: 'blur'
          }
        ],
        nickName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.formData.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        cardId: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        phonenumber: [
          {
            required: true,
            message: '请输入联系方式',
            trigger: 'blur'
          },
          {
            pattern: /(\d{3,4}-?)?\d{7,8}|1\d{10}/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        deptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }
        ],
        postIds: [
          {
            required: true,
            message: '请选择职务',
            trigger: 'change'
          }
        ],
        servicePersonaProportion: [
          {
            required: true,
            message: '分权配重',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9]\d*$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        startData: [
          {
            required: true,
            message: '请选择入职时间',
            trigger: 'change'
          }
        ],
        sex: [
          {
            required: true,
            message: '性别不能为空',
            trigger: 'change'
          }
        ],
        school: [
          {
            required: true,
            message: '请输入毕业院校',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '在职状态不能为空',
            trigger: 'change'
          }
        ],
        servicePersonaFun: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个技能',
            trigger: 'change'
          }
        ],
        addressArr: [
          {
            required: true,
            type: 'array',
            message: '请选择地址',
            trigger: 'change'
          }
        ],
        addressDetail: [
          {
            required: true,
            message: '请输入毕业院校',
            trigger: 'blur'
          }
        ],
        servicePersonalAreas: [
          {
            required: true,
            type: 'array',
            message: '请选择地址',
            trigger: 'change'
          }
        ]
      },
      deptOptions: [],
      postOptions: [],
      sexOptions: [
        {
          label: '男',
          value: 0
        },
        {
          label: '女',
          value: 1
        }
      ],
      statusOptions: [
        {
          label: '否',
          value: 0
        },
        {
          label: '是',
          value: 1
        }
      ],
      servicePersonaFunOptions: [],
      //
      pending: false
    }
  },
  computed: {
    ID() {
      return this.$route.query.id
    }
  },
  async created() {
    getUser().then((response) => {
      this.postOptions = response.posts
    })
    this.getTreeselect()
    this.initDictsOptions('service_personal_fun', 'servicePersonaFunOptions')
  },
  async mounted() {
    if (this.ID) {
      try {
        const res = await fetchApi.detail(this.ID)
        const {province,city,area,...otherData} = res.data
        otherData.servicePersonalAreas = otherData.servicePersonalAreas.map((per) => {
          return CityPicker.methods.getTextToValue(per)
        })
        otherData.addressArr = CityPicker.methods.getTextToValue({
          province,
          city,
          area
        })
        this.formData = Object.assign(this.formData, otherData)
      } catch (error) {
        console.log(error)
      }
    } else {
      this.resetForm()
    }
  },
  // 编辑类不缓存
  // async activated() {
  // },
  methods: {
    async initDictsOptions(dicts, listProps) {
      try {
        const res = await this.getDicts(dicts)
        if (res.code === 200) {
          this[listProps] = res.data.map((per) => ({
            label: per.dictLabel,
            value: per.dictValue
          }))
        }
      } catch (error) {
        console.log(error)
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data
      })
    },
    treeselectChange(row){
      if(row.status==="1"){
        this.msgError("当前部门已停用，暂不能进行选择！");
      }
    },
    getCityObj(addressArr) {
      let cityObj = CityPicker.methods.getValueTextObj(addressArr)
      return cityObj
    },
    handleAreaDataAdd() {
      this.formData.servicePersonalAreas.push([])
    },
    handleAreaDataMinus(index) {
      this.formData.servicePersonalAreas.splice(index, 1)
    },
    submitForm() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        const cityObj = this.getCityObj(this.formData.addressArr)
        const fetchData = {
          ...cityObj,
          ...this.formData
        }
        fetchData.servicePersonalAreas = fetchData.servicePersonalAreas.map(this.getCityObj)
        delete fetchData.checkPass
        delete fetchData.addressArr

        this.pending = true
        try {
          const fetchFn = this.ID ? fetchApi.update : fetchApi.add
          const res = await fetchFn(fetchData)
          if (res.code === 200) {
            this.msgSuccess(res.msg)
            this.$closeNowTagsView()
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .vue-treeselect__control {
  height: 30px;
  line-height: 32px;
}
</style>


